package com.example.book_shop_java.controller;

import com.alibaba.fastjson.JSON;
import com.example.book_shop_java.bean.Address;
import com.example.book_shop_java.dao.AddressDao;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

@RestController
public class AddressController {
    @Resource
    AddressDao addressDao;

    @RequestMapping("/getAllAddress")
    public String getAllAddress(int wx_userid){
        List<Address> addresses = addressDao.getAllAddress(wx_userid);
        String message = "error";
        int code = 413;
        if(addresses.size() > 0){
            code = 200;
            message = "success";
        }
        HashMap<String, Object> res = new HashMap<>();
        res.put("message",message);
        res.put("code",code);
        res.put("data",addresses);
        String allAddressMessage = JSON.toJSONString(res);
        return allAddressMessage;
    }

    @RequestMapping("/addAddress")
    public String addAddress(@RequestParam("wx_userid") int wx_userid,
                             @RequestParam("address") String address,
                             @RequestParam("wx_phone") String wx_phone,
                             @RequestParam("wx_nickname") String wx_nickname){
        System.out.println();
        int i = addressDao.addAddress(wx_userid,address,wx_phone,wx_nickname);
        int code = 413;
        HashMap<String, Object> res = new HashMap<>();
        String message = "error";
        if(i > 0){
            code = 200;
            message = "success";
        }
        res.put("message",message);
        res.put("code",code);
        String addAddressMessage = JSON.toJSONString(res);
        return addAddressMessage;
    }

    @RequestMapping("/deleteAddress")
    public String deleteAddress(int address_id){
        int i = addressDao.deleteAddress(address_id);
        int code = 413;
        HashMap<String, Object> res = new HashMap<>();
        String message = "error";
        if(i > 0){
            code = 200;
            message = "success";
        }
        res.put("message",message);
        res.put("code",code);
        String deleteMessage = JSON.toJSONString(res);
        return deleteMessage;
    }

    @RequestMapping("/getAddress")
    public String getAddress(int address_id){
        List<Address> addresses = addressDao.getAddress(address_id);
        String message = "error";
        int code = 413;
        if(addresses.size() > 0){
            code = 200;
            message = "success";
        }
        HashMap<String, Object> res = new HashMap<>();
        res.put("message",message);
        res.put("code",code);
        res.put("data",addresses);
        String getAddressMessage = JSON.toJSONString(res);
        return getAddressMessage;
    }
}
